package com.carbeauty.common.util;

import java.util.Collection;
import java.util.Random;
import java.util.regex.Pattern;

/**
 * 字符串工具类
 * 
 * 提供常用的字符串操作方法:
 * - 字符串判空和验证
 * - 字符串格式化和转换
 * - 随机字符串生成
 * - 正则表达式验证
 * 
 * @author CarBeauty Team
 */
public class StringUtils {
    
    // ==================== 常用正则表达式 ====================
    
    /**
     * 手机号正则表达式
     */
    public static final String PHONE_REGEX = "^1[3-9]\\d{9}$";
    
    /**
     * 邮箱正则表达式
     */
    public static final String EMAIL_REGEX = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$";
    
    /**
     * 身份证号正则表达式
     */
    public static final String ID_CARD_REGEX = "^[1-9]\\d{5}(18|19|20)\\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$";
    
    /**
     * 车牌号正则表达式
     */
    public static final String CAR_NUMBER_REGEX = "^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z][A-Z0-9]{4}[A-Z0-9挂学警港澳]$";
    
    /**
     * 中文姓名正则表达式
     */
    public static final String CHINESE_NAME_REGEX = "^[\\u4e00-\\u9fa5]{2,10}$";
    
    /**
     * 数字正则表达式
     */
    public static final String NUMBER_REGEX = "^\\d+$";
    
    /**
     * 小数正则表达式
     */
    public static final String DECIMAL_REGEX = "^\\d+(\\.\\d+)?$";
    
    // ==================== 编译后的Pattern ====================
    
    private static final Pattern PHONE_PATTERN = Pattern.compile(PHONE_REGEX);
    private static final Pattern EMAIL_PATTERN = Pattern.compile(EMAIL_REGEX);
    private static final Pattern ID_CARD_PATTERN = Pattern.compile(ID_CARD_REGEX);
    private static final Pattern CAR_NUMBER_PATTERN = Pattern.compile(CAR_NUMBER_REGEX);
    private static final Pattern CHINESE_NAME_PATTERN = Pattern.compile(CHINESE_NAME_REGEX);
    private static final Pattern NUMBER_PATTERN = Pattern.compile(NUMBER_REGEX);
    private static final Pattern DECIMAL_PATTERN = Pattern.compile(DECIMAL_REGEX);
    
    // ==================== 字符串判空 ====================
    
    /**
     * 判断字符串是否为空
     */
    public static boolean isEmpty(String str) {
        return str == null || str.length() == 0;
    }
    
    /**
     * 判断字符串是否不为空
     */
    public static boolean isNotEmpty(String str) {
        return !isEmpty(str);
    }
    
    /**
     * 判断字符串是否为空白（包含空格、制表符等）
     */
    public static boolean isBlank(String str) {
        return str == null || str.trim().length() == 0;
    }
    
    /**
     * 判断字符串是否不为空白
     */
    public static boolean isNotBlank(String str) {
        return !isBlank(str);
    }
    
    /**
     * 判断所有字符串是否都不为空
     */
    public static boolean isAllNotEmpty(String... strs) {
        if (strs == null || strs.length == 0) {
            return false;
        }
        for (String str : strs) {
            if (isEmpty(str)) {
                return false;
            }
        }
        return true;
    }
    
    /**
     * 判断任意字符串是否为空
     */
    public static boolean isAnyEmpty(String... strs) {
        if (strs == null || strs.length == 0) {
            return true;
        }
        for (String str : strs) {
            if (isEmpty(str)) {
                return true;
            }
        }
        return false;
    }
    
    // ==================== 字符串处理 ====================
    
    /**
     * 去除字符串两端空白
     */
    public static String trim(String str) {
        return str != null ? str.trim() : null;
    }
    
    /**
     * 去除字符串两端空白，如果为null则返回空字符串
     */
    public static String trimToEmpty(String str) {
        return str != null ? str.trim() : "";
    }
    
    /**
     * 去除字符串两端空白，如果为空白则返回null
     */
    public static String trimToNull(String str) {
        String trimmed = trim(str);
        return isEmpty(trimmed) ? null : trimmed;
    }
    
    /**
     * 字符串默认值处理
     */
    public static String defaultIfEmpty(String str, String defaultStr) {
        return isEmpty(str) ? defaultStr : str;
    }
    
    /**
     * 字符串默认值处理（空白）
     */
    public static String defaultIfBlank(String str, String defaultStr) {
        return isBlank(str) ? defaultStr : str;
    }
    
    /**
     * 首字母大写
     */
    public static String capitalize(String str) {
        if (isEmpty(str)) {
            return str;
        }
        return str.substring(0, 1).toUpperCase() + str.substring(1);
    }
    
    /**
     * 首字母小写
     */
    public static String uncapitalize(String str) {
        if (isEmpty(str)) {
            return str;
        }
        return str.substring(0, 1).toLowerCase() + str.substring(1);
    }
    
    // ==================== 字符串截取 ====================
    
    /**
     * 安全截取字符串
     */
    public static String substring(String str, int start, int end) {
        if (str == null) {
            return null;
        }
        if (start < 0) {
            start = 0;
        }
        if (end > str.length()) {
            end = str.length();
        }
        if (start > end) {
            return "";
        }
        return str.substring(start, end);
    }
    
    /**
     * 截取指定长度的字符串
     */
    public static String truncate(String str, int maxLength) {
        if (str == null || str.length() <= maxLength) {
            return str;
        }
        return str.substring(0, maxLength);
    }
    
    /**
     * 截取指定长度的字符串并添加省略号
     */
    public static String truncateWithEllipsis(String str, int maxLength) {
        if (str == null || str.length() <= maxLength) {
            return str;
        }
        return str.substring(0, maxLength - 3) + "...";
    }
    
    // ==================== 字符串连接 ====================
    
    /**
     * 连接字符串数组
     */
    public static String join(String[] array, String separator) {
        if (array == null || array.length == 0) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < array.length; i++) {
            if (i > 0) {
                sb.append(separator);
            }
            sb.append(array[i]);
        }
        return sb.toString();
    }
    
    /**
     * 连接集合
     */
    public static String join(Collection<String> collection, String separator) {
        if (collection == null || collection.isEmpty()) {
            return "";
        }
        return String.join(separator, collection);
    }
    
    // ==================== 格式验证 ====================
    
    /**
     * 验证手机号格式
     */
    public static boolean isValidPhone(String phone) {
        return isNotBlank(phone) && PHONE_PATTERN.matcher(phone).matches();
    }
    
    /**
     * 验证邮箱格式
     */
    public static boolean isValidEmail(String email) {
        return isNotBlank(email) && EMAIL_PATTERN.matcher(email).matches();
    }
    
    /**
     * 验证身份证号格式
     */
    public static boolean isValidIdCard(String idCard) {
        return isNotBlank(idCard) && ID_CARD_PATTERN.matcher(idCard).matches();
    }
    
    /**
     * 验证车牌号格式
     */
    public static boolean isValidCarNumber(String carNumber) {
        return isNotBlank(carNumber) && CAR_NUMBER_PATTERN.matcher(carNumber).matches();
    }
    
    /**
     * 验证中文姓名格式
     */
    public static boolean isValidChineseName(String name) {
        return isNotBlank(name) && CHINESE_NAME_PATTERN.matcher(name).matches();
    }
    
    /**
     * 验证是否为数字
     */
    public static boolean isNumber(String str) {
        return isNotBlank(str) && NUMBER_PATTERN.matcher(str).matches();
    }
    
    /**
     * 验证是否为小数
     */
    public static boolean isDecimal(String str) {
        return isNotBlank(str) && DECIMAL_PATTERN.matcher(str).matches();
    }
    
    // ==================== 随机字符串生成 ====================
    
    private static final String NUMBERS = "0123456789";
    private static final String LETTERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private static final String ALPHANUMERIC = NUMBERS + LETTERS;
    
    private static final Random RANDOM = new Random();
    
    /**
     * 生成随机数字字符串
     */
    public static String randomNumbers(int length) {
        return randomString(NUMBERS, length);
    }
    
    /**
     * 生成随机字母字符串
     */
    public static String randomLetters(int length) {
        return randomString(LETTERS, length);
    }
    
    /**
     * 生成随机字母数字字符串
     */
    public static String randomAlphanumeric(int length) {
        return randomString(ALPHANUMERIC, length);
    }
    
    /**
     * 从指定字符集生成随机字符串
     */
    public static String randomString(String chars, int length) {
        if (isEmpty(chars) || length <= 0) {
            return "";
        }
        StringBuilder sb = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            sb.append(chars.charAt(RANDOM.nextInt(chars.length())));
        }
        return sb.toString();
    }
    
    // ==================== 字符串掩码 ====================
    
    /**
     * 手机号掩码处理
     */
    public static String maskPhone(String phone) {
        if (!isValidPhone(phone)) {
            return phone;
        }
        return phone.substring(0, 3) + "****" + phone.substring(7);
    }
    
    /**
     * 邮箱掩码处理
     */
    public static String maskEmail(String email) {
        if (!isValidEmail(email)) {
            return email;
        }
        int atIndex = email.indexOf('@');
        if (atIndex <= 1) {
            return email;
        }
        String username = email.substring(0, atIndex);
        String domain = email.substring(atIndex);
        
        if (username.length() <= 2) {
            return username.charAt(0) + "*" + domain;
        } else {
            return username.charAt(0) + "***" + username.charAt(username.length() - 1) + domain;
        }
    }
    
    /**
     * 身份证号掩码处理
     */
    public static String maskIdCard(String idCard) {
        if (!isValidIdCard(idCard)) {
            return idCard;
        }
        return idCard.substring(0, 6) + "********" + idCard.substring(14);
    }
    
    /**
     * 姓名掩码处理
     */
    public static String maskName(String name) {
        if (isBlank(name)) {
            return name;
        }
        if (name.length() == 1) {
            return name;
        } else if (name.length() == 2) {
            return name.charAt(0) + "*";
        } else {
            return name.charAt(0) + "*".repeat(name.length() - 2) + name.charAt(name.length() - 1);
        }
    }
}
